import turbogears
import re
import datetime
from turbogears import controllers, expose
from quickwiki.model import Page
from docutils.core import publish_parts
from sqlobject import SQLObjectNotFound
# from model import *
# import logging
# log = logging.getLogger("quickwiki.controllers")

wikiwords = re.compile(r"\b([A-Z]\w+[A-Z]+\w+)")

class Root(controllers.RootController):

    @expose(template="quickwiki.templates.page")
    def index(self, pagename="FrontPage"):
        try: 
            page = Page.byPagename(pagename)
        except SQLObjectNotFound:
            raise turbogears.redirect("edit", pagename=pagename)

# parse then view to html
        root = str(turbogears.url('/'))
        data = publish_parts(page.data,writer_name="html")['body']
        data = wikiwords.sub(r'<a href="%s\1">\1</a>' % root, data)
        return dict(data=data, page=page)

    @expose(template="quickwiki.templates.edit")
    def edit(self, pagename):
        try: 
            page = Page.byPagename(pagename)
        except SQLObjectNotFound:
            page = Page(pagename=pagename, data='')
        return dict(page=page)

    @expose()
    def save(self, pagename, data, submit):
        page = Page.byPagename(pagename)
        page.modified = datetime.datetime.now()
# parse for purple then canonicalize to wikitext then save
        page.data = data
        turbogears.flash("Changes saved!")
        raise turbogears.redirect("/%s" % pagename)

    @expose()
    def default(self, pagename):
        return self.index(pagename)

    @expose(template="quickwiki.templates.pagelist", allow_json=True)
    def pagelist(self):
        # XXX: currently sends whole page object which is too much content
        pages = Page.select(orderBy=Page.q.pagename)
        return dict(pages=pages, title="All Pages")

    @expose(template="quickwiki.templates.pagelist", allow_json=True)
    def changes(self):
        # XXX: currently sends whole page object which is too much content
        pages = Page.select(orderBy=Page.q.modified).reversed()[:10]
        return dict(pages=pages, title="Recent Changes")


